// permission.js
import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken } from "@/utils/auth";
import getPageTitle from "@/utils/get-page-title";
import {getUserInfoFromStorage,getTokenFromStorage} from "@/store/modules/user";

NProgress.configure({ showSpinner: false });

const whiteList = ["/login", "/auth-redirect"];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = getPageTitle(to.meta.title);

  const hasToken = getTokenFromStorage();

  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      try {
        // 检查路由是否已加载
        const isRoutesLoaded = store.state.permission.isRoutesLoaded;
        // console.log("路由是否已加载:", isRoutesLoaded,store.getters.permission_routes);
        if (isRoutesLoaded) {
          next();
        } else {
          const userIdHref = to.query.userId;
          let userId = null;
          // 获取并添加路由
          if (userIdHref) {
            userId = userIdHref;
          } else {
            const currentTabUserInfo = getUserInfoFromStorage();
            if (currentTabUserInfo && currentTabUserInfo.userId) {
              userId = currentTabUserInfo.userId;
            } else if (
              store.state.user.userInfo &&
              store.state.user.userInfo.userId
            ) {
              // 回退到 store 中的用户信息
              userId = store.state.user.userInfo.userId;
            } else {
              // 如果都没有找到用户信息，可能是未登录状态
              Message.error("用户信息不完整，请重新登录");
              await store.dispatch("user/resetToken");
              next(`/login?redirect=${to.path}`);
              NProgress.done();
              return;
            }
          }

          const accessRoutes = await store.dispatch(
            "permission/generateRoutesFromAPI",
            userId
          );
          router.addRoutes(accessRoutes);

          // 使用 replace 避免重复导航错误
          next({ ...to, replace: true });
        }
      } catch (error) {
        Message.error("获取用户信息失败，请重新登录");
        await store.dispatch("user/resetToken");
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      if (to.path === "/suittc") {
        sessionStorage.setItem("loginType", "suittc");
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      } else {
        // 其他页面跳转到登录页
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
